"""
Cookies管理器
负责管理cookies的保存、删除、加载等操作
支持多种平台（Facebook、LinkedIn等）的cookies管理
"""
import os
import json
import time
from typing import List, Dict, Any, Optional, Union
from datetime import datetime
from core.utils.logger_manager import LoggerManager
from config.settings import settings
import random
import time

class CookiesManager:
    """Cookies管理器"""
    
    def __init__(self, storage_path: Optional[str] = None):
        """
        初始化Cookies管理器
        
        Args:
            storage_path: cookies存储路径，默认使用配置文件中的路径
        """
        self.logger = LoggerManager.get_logger("cookies_manager")
        self.storage_path = storage_path or settings.cookie_storage_path
        # 确保存储目录存在
        os.makedirs(self.storage_path, exist_ok=True)
    
    def save_cookies(self, platform: str, cookies: List[Dict[str, Any]], 
                    user_id: Optional[str] = None) -> bool:
        """
        保存cookies到文件
        
        Args:
            platform: 平台名称（如facebook、linkedin等）
            cookies: cookies数据列表
            user_id: 用户ID，用于区分不同用户的cookies
            
        Returns:
            bool: 保存是否成功
        """
        try:
        
            # 构建文件名
            filename = self._build_filename(platform, user_id)
            filepath = os.path.join(self.storage_path, filename)
            
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(cookies, f, indent=2, ensure_ascii=False)
            self.logger.info(f"成功保存cookies: {platform}, 数量: {len(cookies)}, 文件: {filename}")
            return True
            
        except Exception as e:
            self.logger.error(f"保存cookies失败: {platform}, 错误: {str(e)}")
            return False
    
    def load_cookies(self, platform: str, user_id: Optional[str] = None) -> Optional[List[Dict[str, Any]]]:
        """
        从文件加载cookies
        
        Args:
            platform: 平台名称
            user_id: 用户ID
            
        Returns:
            List[Dict]: cookies数据列表，如果文件不存在或加载失败返回None
        """
        try:
            filename = self._build_filename(platform, user_id)
            filepath = os.path.join(self.storage_path, filename)
            
            if not os.path.exists(filepath):
                self.logger.warning(f"Cookies文件不存在: {filename}")
                return None
            
            with open(filepath, 'r', encoding='utf-8') as f:
                cookies_data = json.load(f)
            
            # 验证数据格式
            if not isinstance(cookies_data, dict) or 'cookies' not in cookies_data:
                self.logger.error(f"无效的cookies文件格式: {filename}")
                return None
            
            cookies = cookies_data.get('cookies', [])
            self.logger.info(f"成功加载cookies: {platform}, 数量: {len(cookies)}")
            return cookies
            
        except Exception as e:
            self.logger.error(f"加载cookies失败: {platform}, 错误: {str(e)}")
            return None
    
    def delete_cookies(self, platform: str, user_id: Optional[str] = None) -> bool:
        """
        删除cookies文件
        
        Args:
            platform: 平台名称
            user_id: 用户ID
            
        Returns:
            bool: 删除是否成功
        """
        try:
            filename = self._build_filename(platform, user_id)
            filepath = os.path.join(self.storage_path, filename)
            
            if not os.path.exists(filepath):
                self.logger.warning(f"Cookies文件不存在，无需删除: {filename}")
                return True
            
            os.remove(filepath)
            self.logger.info(f"成功删除cookies文件: {filename}")
            return True
            
        except Exception as e:
            self.logger.error(f"删除cookies文件失败: {platform}, 错误: {str(e)}")
            return False
    
    def list_cookies_files(self,platform:str) -> List[Dict[str, Any]]:
        """
        列出所有cookies文件信息
        
        Returns:
            List[Dict]: 文件信息列表
        """
        try:
            files_info = []

            for filename in os.listdir(self.storage_path):
                if filename.endswith('.json') and platform in filename:
                    filepath = os.path.join(self.storage_path, filename)
                    try:
                        with open(filepath, 'r', encoding='utf-8') as f:
                            data = json.load(f)
                        files_info.append(data)
                    except Exception as e:
                        self.logger.warning(f"读取文件信息失败: {filename}, 错误: {str(e)}")
            if files_info:
                return files_info
            else:
                return []
           
            
        except Exception as e:
            self.logger.error(f"列出cookies文件失败: {str(e)}")
            return []
    
    def convert_playwright_cookies(self, playwright_cookies: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        转换Playwright格式的cookies为标准格式
        
        Args:
            playwright_cookies: Playwright格式的cookies
            
        Returns:
            List[Dict]: 标准格式的cookies
        """
        try:
            converted_cookies = []
            
            for cookie in playwright_cookies:
                # 提取必要字段
                converted_cookie = {
                    "name": cookie.get("name", ""),
                    "value": cookie.get("value", ""),
                    "domain": cookie.get("domain", ""),
                    "path": cookie.get("path", "/"),
                    "expires": cookie.get("expires", -1),
                    "httpOnly": cookie.get("httpOnly", False),
                    "secure": cookie.get("secure", True),
                    "sameSite": cookie.get("sameSite", "None")
                }
                
                # 添加可选字段
                if "size" in cookie:
                    converted_cookie["size"] = cookie["size"]
                if "session" in cookie:
                    converted_cookie["session"] = cookie["session"]
                if "priority" in cookie:
                    converted_cookie["priority"] = cookie["priority"]
                if "sameParty" in cookie:
                    converted_cookie["sameParty"] = cookie["sameParty"]
                if "sourcePort" in cookie:
                    converted_cookie["sourcePort"] = cookie["sourcePort"]
                if "sourceScheme" in cookie:
                    converted_cookie["sourceScheme"] = cookie["sourceScheme"]
                
                converted_cookies.append(converted_cookie)
            
            return converted_cookies
            
        except Exception as e:
            self.logger.error(f"转换Playwright cookies失败: {str(e)}")
            return []
    
    def _validate_cookies_format(self, cookies: List[Dict[str, Any]]) -> bool:
        """
        验证cookies数据格式
        
        Args:
            cookies: cookies数据列表
            
        Returns:
            bool: 格式是否有效
        """
        if not isinstance(cookies, list):
            return False
        
        required_fields = ["name", "value", "domain"]
        
        for cookie in cookies:
            if not isinstance(cookie, dict):
                return False
            
            # 检查必需字段
            for field in required_fields:
                if field not in cookie:
                    self.logger.warning(f"缺少必需字段: {field}")
                    return False
        
        return True
    
    def _build_filename(self, platform: str, user_id: Optional[str] = None) -> str:
        """
        构建文件名
        
        Args:
            platform: 平台名称
            user_id: 用户ID
            
        Returns:
            str: 文件名
        """
    
        ts = int(time.time())
       
        if user_id:
            return f"{platform}_{user_id}_{ts}_cookies.json"
        else:
            return f"{platform}_{ts}_cookies.json"
    
    def get_cookies_info(self, platform: str, user_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
        """
        获取cookies文件信息
        
        Args:
            platform: 平台名称
            user_id: 用户ID
            
        Returns:
            Dict: cookies文件信息，如果文件不存在返回None
        """
        try:
            filename = self._build_filename(platform, user_id)
            filepath = os.path.join(self.storage_path, filename)
            
            if not os.path.exists(filepath):
                return None
            
            with open(filepath, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            file_stat = os.stat(filepath)
            
            return {
                "filename": filename,
                "platform": data.get('platform', platform),
                "user_id": data.get('user_id', user_id),
                "count": data.get('count', 0),
                "timestamp": data.get('timestamp'),
                "file_size": file_stat.st_size,
                "modified_time": datetime.fromtimestamp(file_stat.st_mtime).isoformat(),
                "exists": True
            }
            
        except Exception as e:
            self.logger.error(f"获取cookies信息失败: {platform}, 错误: {str(e)}")
            return None


# 全局实例
cookies_manager = CookiesManager()
